package net.maxupeng.asm74.segment;

import net.maxupeng.asm74.antlr.ASM74Parser;

import java.util.ArrayList;
import java.util.List;

import static net.maxupeng.asm74.util.NumberUtil.str2int;

public class BSSSegment extends Segment {
    public BSSSegment(ASM74Parser.ProgContext progCtx) {
        super(progCtx);
    }

    public static List<BSSSegment> parse(List<ASM74Parser.ProgContext> progCtxs) {
        List<BSSSegment> bsses = new ArrayList<>();

        BSSSegment bss = new BSSSegment(null);
        for (ASM74Parser.ProgContext progCtx : progCtxs) {
            boolean isBssSegment = false;
            for (ASM74Parser.LineContext lineCtx : progCtx.line()) {
                if (isBssSegment && lineCtx.label() != null) {
                    bss.ramLabelOffsetMap.put(lineCtx.label().ID().getText(), bss.ramSize);
                }

                if (lineCtx.cmd() != null) {
                    ASM74Parser.CmdContext cmdCtx = lineCtx.cmd();
                    String cmd = cmdCtx.getStart().getText();
                    if (cmd.equals(".segment")) {
                        isBssSegment = cmdCtx.STRING().getText().trim().replaceAll("^\"|\"$", "").toUpperCase().equals("BSSSegment");
                        if (isBssSegment) {
                            bss = new BSSSegment(progCtx);
                            bsses.add(bss);
                        }
                    }

                    if (isBssSegment) {
                        if (cmd.equals(".res")) {
                            bss.ramSize += str2int(cmdCtx.NUMBER(0).getText());
                        }
                    }
                }
            }
        }

        return bsses;
    }
}
